package com.example.demo.easyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.example.demo.easyexcel.dao.BaseUserDAO;
import com.example.demo.easyexcel.dao.BaseUserListener;
import com.example.demo.easyexcel.db.entity.BaseUser;
import com.example.demo.easyexcel.db.repository.CityRepository;
import com.example.demo.easyexcel.util.SelectUtil.EasyExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * @author zjq
 * @version 创建时间：2021-12-17 15:05:13
 */

@Api(tags = {"用户信息模型，这里主要是导入至数据库"})
@RestController
@RequestMapping("/baseUser")
@Slf4j
public class BaseUserController {

    //需要数据处理用这个，这个比较快捷,此Controller专注于数据导入即从excel写入数据库
    @Autowired
    private CityRepository cityRepository;
    @Autowired
    private BaseUserDAO baseUserDAO;

    @ApiOperation(value = "有下拉框的导出数据，存在自定义注解")
    @PostMapping("/exportSelectedExcel")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("用户", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
            WriteSheet writeSheet = EasyExcelUtil.writeSelectedSheet(BaseUser.class, 0, "测试sheet");
            excelWriter.write(new ArrayList<String>(), writeSheet);
            excelWriter.finish();
        } catch (UnsupportedEncodingException e) {
            log.error("导出Excel编码异常", e);
        } catch (IOException e) {
            log.error("导出Excel文件异常", e);
        }
    }

    /**
     * 文件上传
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link BaseUser}
     * <p>
     * 2. 由于默认一行行的读取excel，所以需要创建excel一行一行的回调监听器，参照{@link BaseUserListener}
     * <p>
     * 3. 直接读即可
     */
    @ApiOperation(value = "读取数据，并写入数据库")
    @PostMapping("upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), BaseUser.class, new BaseUserListener(baseUserDAO)).sheet().doRead();
        return "success";
    }


    @ApiOperation(value = "最简单的读取，excel中的数据列需要跟实体类一一对应")
    @PostMapping("upload1")
    @ResponseBody
    public void upload1(MultipartFile file) throws IOException {
        // 写法1：JDK8+ ,不用额外写一个DemoDataListener
        // since: 3.0.0-beta1
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取3000条数据 然后返回过来 直接调用使用数据就行
        EasyExcel.read(file.getInputStream(), BaseUser.class, new PageReadListener<BaseUser>(dataList -> {
            for (BaseUser demoData : dataList) {
                log.info("读取到一条数据{}", JSON.toJSONString(demoData));
            }
        })).sheet().doRead();
    }

}
